<?php
/**
 * Created by PhpStorm.
 * User: ivi
 * Date: 2019/2/23
 * Time: 16:52
 */

namespace App\Utils;


use App\Models\Role;
use App\Repositories\RoleRepository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

/**
 * 权限
 * Class Auth
 * @package App\Utils
 */
class Auth
{

    /**
     * 获取当前登陆用户
     * @return mixed
     */
    public static function userId()
    {
        if (!self::$_userId) {
            self::$_userId = self::userInfo('id', 0);
        }
        return self::$_userId;
    }

    /**
     * 当前部门
     * @return mixed
     */
    public static function departmentId()
    {
        if (!self::$_departmentId) {
            self::$_departmentId = self::userInfo('department_id', 0);
        }
        return self::$_departmentId == 0 ? 1 : self::$_departmentId;
    }

    /**
     * 数据权限控制
     * @param Builder $query
     * @param string $departmentField
     * @param string $userField
     */
    public static function dataAuth($query, $userField = 'user_id')
    {
        if (self::roleTag() == Role::STAFF) {
            $query->where($userField, '=', self::userId());
        }
    }

    /**
     * 当前部门
     * @return mixed
     */
    public static function roleTag()
    {
        if (!self::$_roleTag) {
            self::$_roleTag = self::userInfo('role_tag', '');
        }
        return self::$_roleTag;
    }

    public static function isStaff()
    {
        return Str::startsWith(self::roleTag(), 'staff');
    }

    /**
     * 获取当前登陆用户基础信息
     * @param string $field
     * @param string $default
     * @return mixed
     */
    public static function userInfo($field = '', $default = '')
    {
        if (!self::$_userInfo) {
            self::$_userInfo = session(config('app.adminUserSession'));
        }
        self::$_userInfo;
        if ($field) {
            return Arr::get(self::$_userInfo, $field, $default);
        }
        return self::$_userInfo;
    }

    public static function setMenus()
    {
        $session = request()->session();
        $tag = self::userInfo('role_tag');
        $rep = new RoleRepository();
        $session->put('adminPermissions', $rep->permissions($tag));
        list($menus, $map) = $rep->menus();
        $session->put('adminMenus', $menus);
        $session->put('adminMenusMap', $map);
    }

    public static function getMenus()
    {
        self::setMenus();
        $menus = session('adminMenus');
        if (count($menus)) {
            $menus[0]['open'] = true;
        }
        return $menus;
    }

    public static function isPlat()
    {
        if (Str::startsWith(self::userInfo('role_tag'), 'plat')) {
            return true;
        }
        return false;
    }

    public static function getPermissions()
    {
        return session('adminPermissions', []);
    }

    public static function getMenusMap()
    {
        $uri = request()->controller;
        $map = session('adminMenusMap');
        if (isset($map[$uri])) {
            return Arr::get($map, $uri, []);
        }
        return [];
    }

    /**
     * 系统验证权限
     * @param $action
     * @param string $controller
     * @return bool
     */
    public static function can($action, $controller = '')
    {
        if (self::userId() == 1) return true;
        if (empty($controller)) {
            $rout = Route::getCurrentRoute()->getActionName();
            list($class) = explode('@', $rout);
            $preg = '#App\\\Http\\\Controllers\\\(.*?)Controller#is';
            $match = '';
            \preg_match_all($preg, $class, $match);
            $controller = $match[1][0];
        }
        return self::canAuth($action, $controller);
    }

    /**
     * 系统验证权限
     * @param $action
     * @param string $controller
     * @return bool
     */
    public static function canAuth($action, $controller = '')
    {
        if (self::userId() == 1) return true;
        $permissions = self::getPermissions();
        return isset($permissions[$controller . '@' . $action]);
    }

    private static $_userId;
    private static $_departmentId;
    private static $_roleTag;
    private static $_userInfo;
}
